﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Xml;
using PmfWeb.Core.Utility;

namespace PmfWeb.Core.Cache
{
    /// <summary>
    /// 缓存重写节点列表
    /// </summary>
    public class RewriteHelper
    {
        /// <summary>
        /// 重写文件节点集合
        /// </summary>
        private static Dictionary<string,PmfWeb.Core.Cache.Rewrite> _urls = null;
        /// <summary>
        /// 重写文件存放路径
        /// </summary>
        private static string _xmlPath = "config/rewrite.config";

        /// <summary>
        /// 匹配对象
        /// </summary>
        private static Regex _reg;
        /// <summary>
        /// 私有实例
        /// </summary>
        private static RewriteHelper _helper = null;

        #region 构造器
        /// <summary>
        /// 构造器
        /// </summary>
        private RewriteHelper()
        {
            _urls = new Dictionary<string, PmfWeb.Core.Cache.Rewrite>(100);
            LoadNodes(_xmlPath, FileUtils.FilePathType.DummyPath);
        }

        /// <summary>
        /// 创建重写助手实例
        /// </summary>
        /// <returns></returns>
        public static RewriteHelper Instance()
        {
            if(null == _helper) _helper = new RewriteHelper();
            return _helper;
        }
        #endregion

        #region 加载重写配置信息 public Dictionary<string,Rewrite> LoadNodes(string path, FileUtils.FilePathType pathType)
        ///<summary>
        /// 加载重写配置信息
        ///</summary>
        ///<param name="path">重写配置文件路径</param>
        ///<param name="pathType">路径类型</param>
        ///<returns>重写配置信息</returns>
        public Dictionary<string,PmfWeb.Core.Cache.Rewrite> LoadNodes(string path, FileUtils.FilePathType pathType)
        {
            if (String.IsNullOrEmpty(path)) return null;
            XmlNodeList nodes = FileUtils.LoadXml(path, "root/rewrite", FileUtils.FilePathType.DummyPath);
            if(null == nodes) return null;
            PmfWeb.Core.Cache.Rewrite rewrite = null; 
            foreach (XmlElement o in nodes)
            {
                rewrite = new PmfWeb.Core.Cache.Rewrite();
                rewrite.sKey = o.GetAttribute("key");
                rewrite.SUrl = o.GetAttribute("sUrl");
                rewrite.TUrl = o.GetAttribute("tUrl");
                rewrite.RegUrl = o.GetAttribute("_reg");
                rewrite.IsWrite = Utils.ToBool(o.GetAttribute("isWrite"),true);
                if(!_urls.ContainsKey(rewrite.sKey)) _urls.Add(rewrite.sKey,rewrite);
                rewrite = null;
            }
            return _urls;
        }
        #endregion

        #region 获取匹配的重写路径 public string GetRewritePath(string sPath)
        ///<summary>
        /// 获取匹配的重写路径
        ///</summary>
        ///<param name="sPath">请求的地址</param>
        ///<returns>重写的地址,不存在,返回""</returns>
        public string GetRewritePath(string sPath)
        {
            if (null == _urls) return "";
            string result = "";
            foreach (KeyValuePair<string, PmfWeb.Core.Cache.Rewrite> url in _urls)
            {
                _reg = new Regex(url.Value.RegUrl, RegexOptions.IgnoreCase);
                Match match = _reg.Match(sPath, sPath.LastIndexOf(@"/") + 1);
                if(match.Success)
                {
                    if(!url.Value.IsWrite) break;
                    result = url.Value.TUrl;
                    for (int i = 1; i < match.Groups.Count; i++)
                    {
                        result = result.Replace("$" + i.ToString(), match.Groups[i].Value);
                    }
                    break;
                }
            }
            return result;
        }
        #endregion

        //public void GetCollection()
        //{
        //    SystemWebSectionGroup group =new SystemWebSectionGroup();
        //    HttpModuleActionCollection coll = group.HttpModules.Modules;
        //    //string strModule = "<httpModules>{0}</httpModules>";
        //    //string str = "<add name ='{0}' type = '{1},Common,Version=1.0.0.1,Culture=neutral'>";
        //    bool result = false;
        //    foreach (HttpModuleAction action in coll)
        //    {
        //        if(Utils.ToEquals(action.Name,"Pmf_HttpModule"))
        //        {
        //            result = true;
        //            break;
        //        }
        //    }
        //    if(!result) coll.Add(new HttpModuleAction("Pmf_HttpModule",typeof(Common.Rewrite.UrlRewriteModule).ToString()));
            
        //}
    }
}
